package com.baizhi.service.impl;

import com.baizhi.mapper.AccountMapper;
import com.baizhi.pojo.Account;
import com.baizhi.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Transactional 可以用在方法上也可以用在类上
 *  用在方法上 ：表示该方法支持事务
 *  用在类上：该类中的所有方法都支持事务。不是所有的方法都需要事务，所以一般用在方法上
 */
@Service

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;


    @Override
    @Transactional
    public void transfer(Integer srcId, Integer descId, Integer money) {
        //1. 查询转出账户是否存在，余额是否充足
        Account srcAccount = accountMapper.selectAccountById(srcId);
        //如果srcAccount为空
        if(srcAccount == null){
            System.out.println("账户"+srcId+"不存在");
            return;
        }

        if (srcAccount.getBalance() < money) {
            //余额不足，不能转账
            System.out.println("转账失败，余额不足");
            return;
        }


        //2. 查询转入账户是否存在
        Account descAccount = accountMapper.selectAccountById(descId);
        if(descAccount==null){
            System.out.println("账户"+descId+"不存在");
            return;
        }

        //3.  都正常则转账
       //3.1 修改源账户金额
        int srcNewBalance = srcAccount.getBalance() - money;
        Integer secRows = accountMapper.updateAccountById(srcId,srcNewBalance);

       // int i = 1/0;

        //3.2 修改目标账户金额
        int descNewBalance = descAccount.getBalance() + money;
        Integer descRows = accountMapper.updateAccountById(descId, descNewBalance);

        if(secRows ==1 && descRows==1){
            System.out.println("转账成功");
        }else{
            System.out.println("转账失败");
        }
    }
}
